﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using QD.Data.Json;
using QD.Utils;
using System.Threading;
using System.Web.SessionState;

namespace QD.Web.Ajax
{
    public abstract class AjaxPage : IHttpHandler,IRequiresSessionState 
    {
        protected HttpRequest Request { get; private set; }
        protected HttpResponse Response { get; private set; }
        protected HttpContext Context { get; private set; }

        protected virtual void PageLoad() { }
        protected virtual void PageUnLoad() { }
        public Parse Parse { get; private set; }

        public virtual void ProcessRequest(HttpContext context)
        {
            Context = context;
            Request = context.Request;
            Response = context.Response;
            Parse = new Parse(context.Request);
            PageLoad();
            String _ = Context.Request.QueryString[null];
            if (_ != null) _ = _.ToLower();
            try
            {

                //异常捕获
                AjaxMethodDispatch(_);
            }
            catch (ThreadAbortException e)
            {
                //该异常有Response.End();引起  属于正常  不做处理
            }
            catch (Exception e)
            {
                ErrorCatch(e);
            }
            PageUnLoad();
        }

        /// <summary>
        /// ajax中未捕获的异常处理
        /// </summary>
        /// <param name="e"></param>
        protected virtual void ErrorCatch(Exception e)
        {

        }

        public virtual void AjaxMethodDispatch(string parameter)
        {

        }


        public virtual string ToJson(object obj)
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            return json;
        }

        public virtual object JsonParse(string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject(value); ;
        }

        public virtual T JsonParse<T>(string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region JsonResult

        public virtual void JsonResultJson(int code, string message, JsonBuilder json)
        {
            JsonResultJson(Context, code, message, json.ToString());
        }

       public static void JsonResultJson(HttpContext context, int code, string message = null, object items = null)
        {
            StringBuilder sb = new StringBuilder();
            if (string.IsNullOrEmpty(message))
                message = "";
            sb.AppendFormat("{{\"code\":{0},\"msg\":{1}", code, JsonConvert.SerializeObject(message));
            if (items != null)
                sb.AppendFormat(",\"item\":{0}", items);
            sb.Append("}");
            context.Response.Clear();
            context.Response.Write(sb.ToString());
            context.Response.End();
        }

       public void JsonResultAppend(int code, string message = null, object items = null)
       {
           StringBuilder sb = new StringBuilder();
           if (string.IsNullOrEmpty(message))
               message = "";
           sb.AppendFormat("{{\"code\":{0},\"msg\":{1}", code, JsonConvert.SerializeObject(message));
           if (items != null)
               sb.Append("," + items);
           sb.Append("}");
           Context.Response.Clear();
           Context.Response.Write(sb.ToString());
           Context.Response.End();
       }

        #endregion

        #region Upload

        public virtual void JsonResultUpload(int code, string message = null, string url = null)
        {
            JsonResultUpload(Context, code, message, url);
        }

        private static void JsonResultUpload(HttpContext context, int code, string message = null, string url = null)
        {
            StringBuilder sb = new StringBuilder();
            if (string.IsNullOrEmpty(message))
                message = "";
            sb.AppendFormat("{{\"code\":{0},\"msg\":{1},\"url\":{2}}}", code, JsonConvert.SerializeObject(message), JsonConvert.SerializeObject(url));
            context.Response.Clear();
            context.Response.Write(sb.ToString());
            context.Response.End();
        }

        #endregion

        #region JsonResult

        public virtual void JsonResultPage(int code, string message = null, int? total = null, int? currentpage = null, int? pagesize = null, params object[] item)
        {
            StringBuilder sb = new StringBuilder();
            if (string.IsNullOrEmpty(message))
                message = "";
            if (!total.HasValue)
                total = 0;
            sb.AppendFormat("{{\"code\":{0},\"msg\":{1},\"total\":{2},\"currentpage\":{3},\"pagesize\":{4}", code, JsonConvert.SerializeObject(message), total.Value, currentpage.Value, pagesize.Value);
            if (item != null)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    sb.AppendFormat(",\"item{1}\":{0}", JsonConvert.SerializeObject(item[i]), i == 0 ? "" : i.ToString());
                }
            }
            sb.Append("}");
            Context.Response.Clear();
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }

        public virtual void JsonResult(int code, string message = null, params object[] item)
        {
            JsonResult(Context, code, message, null, item);
        }

        public virtual void JsonResultRow(int code, string message = null, int? row_count = null, params object[] item)
        {
            JsonResult(Context, code, message, row_count, item);
        }

        private static void JsonResult(HttpContext context, int code, string message = null, int? row_count = null, params object[] item)
        {

            StringBuilder sb = new StringBuilder();
            if (string.IsNullOrEmpty(message))
                message = "";
            if (row_count.HasValue)
                sb.AppendFormat("{{\"code\":{0},\"msg\":{1},\"row_count\":{2}", code, JsonConvert.SerializeObject(message), row_count);
            else
                sb.AppendFormat("{{\"code\":{0},\"msg\":{1}", code, JsonConvert.SerializeObject(message));
            if (item != null)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    sb.AppendFormat(",\"item{1}\":{0}", JsonConvert.SerializeObject(item[i]), i == 0 ? "" : i.ToString());
                }

            }
            sb.Append("}");
            context.Response.Clear();
            context.Response.Write(sb.ToString());
            context.Response.End();
        }
        #endregion
    }
}
